package com.yonyou.cyxdms.sysAuth.service.service.gathering.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.gathering.GatheringTypeDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.gathering.GatheringTypePO;
import com.yonyou.cyxdms.sysAuth.service.mapper.gathering.GatheringTypeMapper;
import com.yonyou.cyxdms.sysAuth.service.service.gathering.GatheringTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author adu
 * @since 2019-11-04
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GatheringTypeServiceImpl extends ServiceImpl<GatheringTypeMapper, GatheringTypePO> implements GatheringTypeService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(GatheringTypeServiceImpl.class);
    @Autowired
    GatheringTypeMapper gatheringTypeMapper;

    /**
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     * @author adu
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        // 获取总条数
        if (loginInfoDto.getDataType() == ManageDictCodeConstants.DATA_TYPE_BY_OWNER) {
            queryCondition.put("validStatus", ManageDictCodeConstants.STATUS_IS_VALID);
        }
        page.setRecords(gatheringTypeMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author adu
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> selectListBySql(Map<String, Object> queryCondition) {
        return gatheringTypeMapper.selectListBySql(queryCondition);
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param id 主键ID
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author adu
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Long id) {
        GatheringTypePO gatheringtypepo = gatheringTypeMapper.selectById(id);
        if (gatheringtypepo != null) {
            return gatheringtypepo.toMaps();
        } else {
            throw new DALException("查询失败,没有符合条件的数据");
        }
    }

    /**
     * 根据DTO 进行数据新增
     *
     * @param gatheringTypeDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> insert(GatheringTypeDTO gatheringTypeDTO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        //查重-结算编码和名称不可以重复
        String gatheringCode = gatheringTypeDTO.getGatheringCode();
        String gatheringName = gatheringTypeDTO.getGatheringName();
        checkCodeAndName(gatheringTypeDTO);
        if (repeatCode(gatheringCode, gatheringName)) {
            //对对象进行赋值操作
            GatheringTypePO gatheringtypepo = gatheringTypeDTO.transDtoToPo(GatheringTypePO.class);
            gatheringtypepo.setAppId(loginInfo.getAppId());
            gatheringtypepo.setCompanyId(loginInfo.getCompanyId());
            gatheringtypepo.setOwnerCode(loginInfo.getOwnerCode());
            gatheringtypepo.setDataSource(ManageDictCodeConstants.DATA_SOURCES_BY_SUPER);
            gatheringtypepo.setDataType(SysAuthDictCodeConstants.DATA_TYPE_BY_SUPER);
            gatheringtypepo.setValidStatus(CommonConstants.DEALER_ATTACH_STATUS_ENABLE);//默认有效
            gatheringtypepo.setCreatedBy(loginInfo.getUserName());
            gatheringtypepo.setUpdatedBy(loginInfo.getUserName());
            //执行插入
            gatheringTypeMapper.insert(gatheringtypepo);
            //返回插入的值
            return gatheringTypeMapper.selectById(gatheringtypepo.getGatheringId()).toMaps();
        } else {
            throw new ServiceBizException("结算编码或结算名称不能重复");
        }
    }

    public void checkCodeAndName(GatheringTypeDTO gatheringTypeDTO) {
        if (StringUtils.isNullOrEmpty(gatheringTypeDTO.getGatheringCode())) {
            throw new ServiceBizException("结算编码");
        }
        if (StringUtils.isNullOrEmpty(gatheringTypeDTO.getGatheringName())) {
            throw new ServiceBizException("结算名称");
        }
    }

    /**
     * 判断是否存在已有的结算编码和名称
     *
     * @author adu
     * @since 2019/9/19
     */
    private boolean repeatCode(String gatheringCode, String gatheringName) {
        LambdaQueryWrapper<GatheringTypePO> queryWrapper = new QueryWrapper<GatheringTypePO>().lambda();
        queryWrapper.eq(GatheringTypePO::getGatheringCode, gatheringCode);
        List<GatheringTypePO> gatheringtypepos = gatheringTypeMapper.selectList(queryWrapper);
        //boolean flag = CommonUtils.isNullOrEmpty(gatheringTypePOS);
        if (gatheringtypepos.size() > 0) {
            return false;
        } else {
            LambdaQueryWrapper<GatheringTypePO> queryWrapper1 = new QueryWrapper<GatheringTypePO>().lambda();
            queryWrapper1.eq(GatheringTypePO::getGatheringName, gatheringName);
            List<GatheringTypePO> gatheringtypepos1 = gatheringTypeMapper.selectList(queryWrapper1);
            if (gatheringtypepos1.size() > 0) {
                return false;
            }
            return true;
        }

    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id               主键ID
     * @param gatheringTypeDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> update(Long id, GatheringTypeDTO gatheringTypeDTO) {
        GatheringTypePO gatheringtypepo = gatheringTypeMapper.selectById(id);
        if (null != gatheringtypepo) {
            gatheringtypepo.setGatheringCode(gatheringTypeDTO.getGatheringCode());
            gatheringtypepo.setGatheringName(gatheringTypeDTO.getGatheringName());
            gatheringtypepo.setIsPay(gatheringTypeDTO.getIsPay());
            gatheringtypepo.setIsReceive(gatheringTypeDTO.getIsReceive());
            if(!StringUtils.isNullOrEmpty(gatheringTypeDTO.getWriteoffTag())){
                gatheringtypepo.setWriteoffTag(gatheringTypeDTO.getWriteoffTag());
            }
            if(!StringUtils.isNullOrEmpty(gatheringTypeDTO.getValidStatus())){
                gatheringtypepo.setValidStatus(gatheringTypeDTO.getValidStatus());
            }
            //执行更新
            gatheringTypeMapper.updateById(gatheringtypepo);
        }

        return gatheringtypepo.toMaps();
    }

    /**
     * 根据ID 进行删除数据
     *
     * @param id
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    public void deleteById(Long id) {
        int deleteCount = gatheringTypeMapper.deleteById(id);
        logger.debug("删除数量：{}", deleteCount);
        if (deleteCount <= 0) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    /**
     * 根据ids 进行删除
     *
     * @param ids
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    public void deleteBatchIds(String ids) {
        List<Long> longList = StringUtils.convertStrToArray(ids, ",", Long.class);
        int deleteCount = gatheringTypeMapper.deleteBatchIds(longList);
        logger.debug("删除数量：{}", deleteCount);
        if (deleteCount != longList.size()) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }
}
